package com.wq.designer.lessif;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: wangqiang20995
 * @Date:2018/10/24
 * @Description:
 * @Resource:
 */
public class ServiceManager implements Manager<Service> {

    Map<Class<Service>, Service> register;

    public ServiceManager() {
        register = new ConcurrentHashMap<>();
    }


    @Override
    public boolean register(Service service) {
        return register.putIfAbsent((Class<Service>) service.getClass(), service) == null;
    }

    @Override
    public void chooseAndExecute(Support support) {
        if (register.size() == 0) {
            System.out.println("empty list and no service is registered");
            return;
        }

        Iterator<Map.Entry<Class<Service>, Service>> iterator = register.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Class<Service>, Service> entry = iterator.next();
            Service service = entry.getValue();
            if (service.condition(support)) {
                System.out.println("first match condition --> [" + support + "]");
                service.execute();
                break;
            }
        }
    }

    public static void main(String args[]) {
        Manager<Service> manager = new ServiceManager();
        Service china = new ChineseService();
        Service english = new EnglishService();
        Service france = new FranceService();
        manager.register(china);
        manager.register(english);
        manager.register(france);

        Support condition = new Support();
        condition.setType("China");
        condition.setCondition("0");
        manager.chooseAndExecute(condition);
    }
}
